package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.dto.ScrollResult;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IUserService;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

import static com.hmdp.utils.RedisConstants.BLOG_LIKED_KEY;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @since 2021-12-22
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {

    @Resource
    private IUserService userService;

    @Resource
    private IBlogService blogService;

    @Resource
    StringRedisTemplate stringRedisTemplate;
    @Resource
    private FollowServiceImpl followService;

    @Override
    public Result queryBlogByUserId(Integer id, Integer current) {
        Page<Blog> page = query().eq("user_id", id).page(new Page<>(current,SystemConstants.MAX_PAGE_SIZE));
        List<Blog> blogs=page.getRecords();
        return Result.ok(blogs);
    }

    //查询点赞的前四个用户
    @Override
    public Result queryLikesUser(Long id) {
        String key = id + BLOG_LIKED_KEY;
        Set<String> userSet= stringRedisTemplate.opsForZSet().range(key,0,4);
        if (userSet==null||userSet.isEmpty()){
          return Result.ok(Collections.emptyList());
      }
        List<Long> userList = userSet.stream().map(Long::valueOf).collect(Collectors.toList());//stream流将String的Set集合转化为Long的List集合
        List<UserDTO> userDTOs=userList.stream().map(user -> BeanUtil.copyProperties(user,UserDTO.class))
                .collect(Collectors.toList());

        return Result.ok(userDTOs);
    }

    //在主页面展示热门博客
    @Override
    public Result queryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = blogService.query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog ->{
            Long userId = blog.getUserId();
            User user = userService.getById(userId);
            blog.setName(user.getNickName());
            blog.setIcon(user.getIcon());
            isBlogLiked(blog);
        });

        return Result.ok(records);
    }

    //判断当前用户是否点赞该博客
    @Override
    public void isBlogLiked(Blog blog) {
        String blogId = blog.getId().toString();
        String key = blogId + BLOG_LIKED_KEY;
        UserDTO user = UserHolder.getUser();//获取登录用户的id
        if (user==null){
            return; //没登陆不用查询是否点赞，不然没登陆会报空指针的错误
        }
        String userId = user.getId().toString();
        Double score = stringRedisTemplate.opsForZSet().score(key, userId);
        blog.setIsLike(score!=null);
    }

    //查询关注者的博客
    @Override
    public Result queryBlogOfFollow(Long max, Integer offset) {
        Long id1 = UserHolder.getUser().getId();
        String key="feed"+id1;
        //博客的分页集合
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet()
                .reverseRangeByScoreWithScores(key, 0, max, offset, 2);
        if (typedTuples==null||typedTuples.isEmpty()){
            return Result.ok();
        }
        ArrayList<Long> ids = new ArrayList<>();
        //因为是从大到小排好的，所以最后min为最小的score
        int os=0;
        long min=0;
        for (ZSetOperations.TypedTuple<String> tuple:typedTuples) {
            long score = tuple.getScore().longValue();
            ids.add(Long.valueOf(tuple.getValue()));

            if (score == min) {
                os++;
            } else {
                min = score;
                os = 1;
            }
        }
            //返回给前端的数据,博客要按照时间戳排序放在集合里
        String idStr = StrUtil.join(",", ids);//将ids集合中的元素用逗号连成一个字符串
        List<Blog> blogs= query().in("id",ids).last("ORDER BY FIELD(id,"+ idStr+")").list();
        for (Blog blog:blogs) {
            queryLikesUser(blog.getId());
            isBlogLiked( blog);

        }
            ScrollResult scrollResult = new ScrollResult();
            scrollResult.setList(blogs);
            scrollResult.setMinTime(min);
            scrollResult.setOffset(os);

        return Result.ok(scrollResult);
    }

    //保存博客并推送给粉丝
    @Override
    public Result saveBlog(Blog blog) {
        UserDTO user = UserHolder.getUser();
        blog.setUserId(user.getId());
        // 保存探店博文到mysql
        blogService.save(blog);
        //查询所有的粉丝
        List<Follow> followList= followService.query().eq("follow_user_id", user.getId()).list();
        for (Follow f:followList) {
            Long userId = f.getUserId();
            String key="feed"+userId;
            stringRedisTemplate.opsForZSet().add(key,blog.getId().toString(),System.currentTimeMillis());
        }
        // 返回id
        return Result.ok(blog.getId());
    }

    //给博客进行点赞或取消赞
    @Override
    public void likeBlog(Long id) {
        String userId = UserHolder.getUser().getId().toString();//获取登录用户的id
        String key = id + BLOG_LIKED_KEY;
        Double score = stringRedisTemplate.opsForZSet().score(key, userId);//获取分数
        if (score==null) {
            // 不存在，说明没点过赞
            boolean isSuccess = blogService.update()
                    .setSql("liked = liked + 1").eq("id", id).update();
            if (isSuccess) {
                stringRedisTemplate.opsForZSet().add(key, userId,System.currentTimeMillis());
            }
        } else {
            //存在就减一并删除redis里的数据
            boolean isSuccess = blogService.update()
                    .setSql("liked = liked - 1").eq("id", id).update();
            if (isSuccess) {
                stringRedisTemplate.opsForZSet().remove(key, userId);
            }
        }
    }

    @Override
    public Result queryBlogById(Long id) {
        Blog blog = getById(id);
        if (blog==null){
            return Result.fail("博客不存在");
        }

        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setIcon(user.getIcon());
        blog.setName(user.getNickName());
        isBlogLiked(blog);
        return Result.ok(blog);

    }
}
